
package com.joolun.cloud.mall.api.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joolun.cloud.common.core.constant.CommonConstants;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.mall.api.mapper.UserCollectMapper;
import com.joolun.cloud.mall.api.util.ThirdSessionHolder;
import com.joolun.cloud.mall.common.constant.MallConstants;
import com.joolun.cloud.mall.common.constant.MyReturnCode;
import com.joolun.cloud.mall.common.entity.ShopInfo;
import com.joolun.cloud.mall.api.service.ShopInfoService;
import com.joolun.cloud.mall.common.entity.UserCollect;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 店铺表
 *
 * @author www.joolun.com
 * @date 2020-05-15 14:35:53
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/shopinfo")
@Api(value = "shopinfo", tags = "店铺API")
public class ShopInfoController {

    private final ShopInfoService shopInfoService;
	private final UserCollectMapper userCollectMapper;

    /**
     * 分页列表
     * @param page 分页对象
     * @param shopInfo 店铺表
     * @return
     */
    @ApiOperation(value = "分页列表")
    @GetMapping("/page")
    public R getPage(Page page, ShopInfo shopInfo) {
		shopInfo.setEnable(CommonConstants.YES);
        return R.ok(shopInfoService.page(page, Wrappers.query(shopInfo)));
    }

	/**
	 * 分页列表
	 * @param page 分页对象
	 * @param shopInfo 店铺表
	 * @return
	 */
	@ApiOperation(value = "分页列表")
	@GetMapping("/pagewithspu")
	public R getPageWithSpu(Page page, ShopInfo shopInfo) {
		shopInfo.setEnable(CommonConstants.YES);
		return R.ok(shopInfoService.pageWithSpu(page, shopInfo));
	}

    /**
     * 店铺表查询
     * @param id
     * @return R
     */
    @ApiOperation(value = "店铺表查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") String id) {
		ShopInfo shopInfo = shopInfoService.getById(id);
		if(shopInfo == null){
			return R.failed(MyReturnCode.ERR_80044.getCode(), MyReturnCode.ERR_80044.getMsg());
		}
		int count = userCollectMapper.selectCount(Wrappers.<UserCollect>lambdaQuery()
						.eq(UserCollect::getRelationId,shopInfo.getId()));
		shopInfo.setCollectCount(count);
		//查询用户是否收藏
		String userId = ThirdSessionHolder.getUserId();
		if(StrUtil.isNotBlank(userId)){
			UserCollect userCollect = new UserCollect();
			userCollect.setUserId(userId);
			userCollect.setType(MallConstants.COLLECT_TYPE_2);
			userCollect.setRelationId(id);
			shopInfo.setCollectId(userCollectMapper.selectCollectId(userCollect));
		}
        return R.ok(shopInfo);
    }

}
